package org.alis.ap.rpc.client.selector;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.alis.ap.rpc.Peer;
import org.alis.ap.rpc.transport.TransportClient;
import org.alis.ap.rpc.transport.http.ApTransportClient;
import org.alis.ap.rpc.utils.ReflectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.IntStream;

/**
 * RandomTransportSelector desc: 随机算法
 *
 * @author luochuan
 * @date 2020/10/21 13:48
 */
@Slf4j
public class RandomTransportSelector implements TransportSelector {
    /**
     * 表示已经链接的client
     */
    private List<TransportClient> clientList;

    public RandomTransportSelector() {
        clientList = Collections.synchronizedList(Lists.newArrayList());
    }

    @Override
    public void init(List<Peer> peerList, int count, Class<? extends TransportClient> clazz) {
        int size = Math.max(count, 1);
        peerList.forEach(peer -> IntStream.range(0, size).forEach(index -> {
            TransportClient client = ReflectionUtils.newInstance(ApTransportClient.class);
            client.connect(peer);
            clientList.add(client);
            log.info("connect server:{}", peer);
        }));
    }

    @Override
    public TransportClient select() {
        int i = new Random().nextInt(clientList.size());
        return clientList.remove(i);
    }

    @Override
    public void release(TransportClient client) {
        clientList.add(client);
    }

    @Override
    public void close() {
        clientList.forEach(TransportClient::disconnect);
        clientList.clear();
    }
}
